<template>
    <span @click="() => { if (disabled) return; show = true }">
        {{ text ? text : placeholder ? '请选择' + placeholder : '请选择' }}</span>
    <Popup :show="show" position="bottom" @click-overlay="show = false">
        <!-- 已选择 -->
        <div v-if="multiple && Array.isArray(value)"
            style="padding: 10px;display: flex;align-items: center;justify-content: space-between">
            <div>
                <span v-for="item, index in options" :key="index" style="margin-right: 12px;">
                    <template v-if="value.includes(item[valueName])">
                        {{ item[labelName] }}
                        <Icon name="close" @click="() => onCancal(index - 1)" style="margin-left: 4px;" />
                    </template>
                </span>
            </div>
            <Button size="mini" type="primary" @click="onConfirm">确认</Button>
        </div>
        <Field v-if="inputable" v-model="checked[0]" :label="'新建' + placeholder" :placeholder="'请输入' + placeholder">
        </Field>
        <Picker v-model="checked" :columns="options" :columnsFieldNames="columnsFieldNames" @confirm="confirm"
            @cancel="show = false"></Picker>
    </Popup>
</template>
<script setup lang="ts">
import { Popup, Field, Picker, Icon, Button } from "vant";
import type { PickerOption } from "vant";
import { ref } from "vue";
import type { Ref } from "vue";
interface prop {
    inputable?: boolean
    options: PickerOption[]
    placeholder?: string
    props?: { label?: string, value?: string }
    disabled?: boolean
    multiple?: boolean
    value: number | string | Array<number | string>
}
const { value, multiple, options, props } = defineProps<prop>()
let v: (number | string)[] = []
const columnsFieldNames = props ? { text: props?.label, value: props?.value } : { text: 'label', value: 'value' }

let lastValue: string | number = ''
if (Array.isArray(value)) {
    lastValue = value[value.length - 1]
    v = value
} else {
    lastValue = value || ''
    v = [value]
}

const checked: Ref<(number | string)[]> = ref([lastValue || ''])
const emits = defineEmits<{
    (e: 'confirm', v: typeof value): void
}>()
const labelName = props?.label || 'label'
const valueName = props?.value || 'value'
const show = ref(false)
const text = ref('')

const getText = () => options.filter(item => v.includes(item[valueName])).map(item => item[labelName]).join(',')
text.value = getText()

const onCancal = (index: number) => {
    if (!multiple) return
    v.splice(index, 1)
}
const confirm = () => {
    if (multiple) {
        v.push(checked.value[0])
    } else {
        v = checked.value
        onConfirm()
    }
}
const onConfirm = () => {
    show.value = false
    text.value = getText()
    emits('confirm', v)
}
</script>
